package dev.pda.display.presentation.splash

import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.jeremyliao.liveeventbus.LiveEventBus
import com.liulishuo.okdownload.kotlin.listener.createDownloadContextListener
import dev.pda.display.Constants
import dev.pda.display.R
import dev.pda.display.presentation.common.base.BaseViewModelActivity
import dev.pda.display.presentation.page.PageFragment
import dev.pda.display.presentation.page.model.ResourceVM
import dev.pda.display.util.queue.QueueController
import dev.pda.display.util.queue.QueueRecyclerAdapter
import kotlinx.android.synthetic.main.activity_main.*

class SplashActivity : BaseViewModelActivity<SplashViewModel>() {

    private var controller: QueueController? = null
    private var adapter: QueueRecyclerAdapter? = null

    override fun buildViewModel(): SplashViewModel {
        val viewModel by viewModels<SplashViewModel> {
            SplashViewModelFactory()
        }
        return viewModel
    }

    override fun initObserve() {
        viewModel.resourceVMListLiveData.observe(this, {
            initController(it)
        })
        viewModel.parserResourceMessage(Constants.TEST_DATA)
        LiveEventBus
            .get(Constants.RECEIVER_TCP_MESSAGE)
            .observe(this, Observer {
                viewModel.parserResourceMessage(it.toString())
            })
    }

    override fun getContentResource(): Int {
        return R.layout.activity_main
    }

    private fun initView() {
        rv.layoutManager = LinearLayoutManager(this)
        controller?.let {
            val adapter = QueueRecyclerAdapter(it)
            this.adapter = adapter
            rv.adapter = adapter
        }
    }

    private fun initController(resourceVMList: List<ResourceVM>) {
        val controller = QueueController()
        this.controller = controller
        controller.initTasks(this, resourceVMList, createDownloadContextListener {
            controller.stop()
            adapter?.notifyDataSetChanged()
            llLoading.isVisible = false
            loadPageFragment()
        })
        initView()
        this.controller?.start(true)
        adapter?.notifyDataSetChanged()
    }

    private fun loadPageFragment() {
        val fragment = PageFragment.newInstance(viewModel.programVM?.widgetModels)
        fl.layoutParams = viewModel.programVM?.screenHeight?.toInt()?.let {
            viewModel.programVM?.screenWidth?.toInt()?.let { it1 ->
                LinearLayout.LayoutParams(
                    it1,
                    it
                )
            }
        }
        supportFragmentManager
            .beginTransaction()
            .add(R.id.fl, fragment)
            .commitAllowingStateLoss()
    }

    override fun onDestroy() {
        super.onDestroy()
        controller?.stop()
    }
}